<template>
  <div class="form-container">
    <!-- 添加标题 -->
    <div class="header">编辑舞萌中二出勤信息</div>
    <!-- 添加带下划线的文字 -->
    <p class="form-description">所有内容都不允许为空，最多可以上传6张图片</p>

    <el-form
        ref="form"
        :model="form"
        class="responsive-form"
        label-position="left"
        label-width="120px"
    >
      <!-- 店铺名字 -->
      <el-form-item label="店铺名字" prop="shopName">
        <el-input v-model="form.shopName" placeholder="请输入店铺名字哦（在天津有多个分店的要标注清楚）"></el-input>
      </el-form-item>
      <el-form-item label="游戏分类" prop="gameCategory">
        <el-select v-model="form.gameCategory" placeholder="请选择游戏分类（目前仅支持舞萌，中二）">
          <el-option label="舞萌DX" value="舞萌DX"></el-option>
          <el-option label="中二节奏" value="中二节奏"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="游戏价格" prop="gamePrice">
        <el-select v-model="form.gamePrice" placeholder="请选择游戏价格（多少币1pc，免费选0）">
          <el-option v-for="price in prices" :key="price" :label="price" :value="price"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="游戏描述" prop="gameDescription">
        <el-input v-model="form.gameDescription"
                  placeholder="请输入游戏描述（先写营业时间段，如10:00-21:00，再写机况等内容）"
                  type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="位置指引" prop="gameGuidePosition">
        <el-input v-model="form.gameGuidePosition"
                  placeholder="请输入游戏指引位置（这里可以写坐哪几号线地铁，可以坐哪几号公交到达，以及到室内怎么找机台）"></el-input>
      </el-form-item>
      <el-form-item label="内容图片" prop="contentImage">
        <el-upload
            :action=this.uploadUrl
            :before-upload="beforeUpload"
            :file-list="fileList"
            :limit="6"
            :on-change="handleChange"
            :on-error="handleError"
            :on-exceed="handleExceed"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            accept="image/*"
            list-type="picture-card"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
      <!-- 提交按钮 -->
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {ElMessage} from "element-plus";
import axios from "axios";
import {inject} from "vue";

export default {
  setup() {
    const uploadUrl = inject("uploadUrl");
    return {uploadUrl};
  },
  data() {
    return {
      form: {
        shopName: '',
        gameCategory: '',
        gamePrice: null,
        gameDescription: '',
        gameGuidePosition: '',
        contentImage: [], // 存储图片的 URL
      },
      fileList: [], // 文件列表，用于显示上传的图片
      dialogImageUrl: '', // 预览图片的 URL
      dialogVisible: false, // 控制预览对话框的显示
      prices: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] // 游戏价格选项
    };
  },
  mounted() {
    //数据回显，初始化数据
    this.getOriginalData();
  },
  methods: {
    getOriginalData() {
      const id = this.$route.query.mcId;
      axios.get('/maimaiChunithm/get/' + id)
          .then(response => {
            const OriginalData = response.data.data;
            this.form.shopName = OriginalData.shopName;
            this.form.gameCategory = OriginalData.gameCategory;
            this.form.gamePrice = OriginalData.gamePrice;
            this.form.gameDescription = OriginalData.gameDescription;
            this.form.gameGuidePosition = OriginalData.gameGuidePosition;
            // 将原始的 contentImage 字符串转换为数组
            this.form.contentImage = JSON.parse(OriginalData.contentImage);
            // 将 contentImage 数组转换为 fileList 格式
            if (this.form.contentImage && this.form.contentImage.length > 0) {
              this.fileList = this.form.contentImage.map((url, index) => ({
                name: `image_${index + 1}`, // 文件名
                url: url, // 图片 URL
                status: 'success', // 上传状态
              }));
            } else {
              this.fileList = [];
            }
          })
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 移除图片
    handleRemove(file, fileList) {
      // 从 form.contentImage 中移除对应的图片 URL
      const index = this.form.contentImage.indexOf(file.url);
      if (index !== -1) {
        this.form.contentImage.splice(index, 1);
      }
      this.fileList = fileList; // 更新 fileList 状态
    },
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt8M = file.size / 1024 / 1024 < 8; // 文件大小限制为 8MB
      if (!isImage) {
        ElMessage.error('只能上传图片格式的文件!');
        return false; // 阻止上传
      }
      if (!isLt8M) {
        ElMessage.error('上传的图片大小不能超过 8MB!');
        return false; // 阻止上传
      }
      return true; // 允许上传
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      ElMessage.success('上传成功');
      // 假设上传成功后，后端返回图片的 URL
      this.form.contentImage.push(response.data); // 将返回的 URL 添加到 form.contentImage 中
      this.fileList = fileList; // 更新 fileList 状态
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      ElMessage.error('上传失败');
      console.error('上传失败', err);
    },
    // 超出上传限制时的回调
    handleExceed(files, fileList) {
      ElMessage.warning('最多只能上传 6 张图片');
    },
    // 文件状态变化时的回调
    handleChange(file, fileList) {
      // 如果是新增文件，先将文件对象存储起来，等待上传成功后再更新 URL
      if (file.status === 'ready') {
        this.fileList = fileList; // 更新 fileList 状态
      }
    },
    // 提交表单
    onSubmit() {
      if (this.form.shopName === '' || this.form.gameCategory === '' ||
          this.form.gamePrice === null || this.form.gameDescription === ''
          || this.form.gameGuidePosition === '' || this.form.contentImage.length === 0) {
        ElMessage.error('所有内容都不许为空哦');
        return;
      }
      const id = this.$route.query.mcId;
      axios.put('/maimaiChunithm/update/' + id, {
        shopName: this.form.shopName,
        gameCategory: this.form.gameCategory,
        gamePrice: this.form.gamePrice,
        gameDescription: this.form.gameDescription,
        gameGuidePosition: this.form.gameGuidePosition,
        contentImage: JSON.stringify(this.form.contentImage), // 转换为 JSON 字符串
      })
          .then(response => {
            console.log(response.data);
            ElMessage.success('更新成功');
            this.$router.push('/MaimaiChunithmSelect');
          })
          .catch(error => {
            console.error(error);
            ElMessage.error('添加失败');
          });
    },
  }
}
</script>

<style scoped>
.form-container {
  margin: 20px 0; /* 调整外边距，使其向左对齐 */
  padding: 20px;
}

/* 添加标题样式 */
.header {
  background: none;
  padding-top: 5px;
  text-align: left;
  font-size: 20px;
  line-height: 30px;
  font-weight: bold;
}

/* 添加带下划线的文字样式 */
.form-description {
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
  color: #666;
  text-align: left;
  line-height: 25px; /* 设置行高 */
}

.responsive-form {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 强制设置 placeholder 字体为 Zpix */
.form-container ::placeholder {
  font-family: "Zpix", sans-serif !important;
}

/* 强制设置输入框内容的字体为 Zpix */
.form-container input {
  font-family: "Zpix", sans-serif !important;
}
</style>